const ResultCode = {
  SUCCESS: { code: 200, message: '操作成功' },
  PARAM_ERROR: { code: 400, message: '参数错误' },
  UNAUTHORIZED: { code: 401, message: '未授权' },
  FORBIDDEN: { code: 403, message: '禁止访问' },
  NOT_FOUND: { code: 404, message: '资源不存在' },
  SERVER_ERROR: { code: 500, message: '服务器内部错误' },
  
  // 业务错误码
  INVALID_CREDENTIALS: { code: 1001, message: '用户名或密码错误' },
  USER_EXISTS: { code: 1002, message: '用户已存在' },
  CATEGORY_EXISTS: { code: 2001, message: '分类已存在' },
  CATEGORY_NOT_EMPTY: { code: 2002, message: '分类下存在商品' },
  PRODUCT_EXISTS: { code: 3001, message: '商品已存在' },
  ORDER_STATUS_ERROR: { code: 4001, message: '订单状态错误' }
};

/**
 * API响应封装类
 */
class ApiResponse {
  /**
   * 成功响应
   * @param {*} data 响应数据
   * @param {string} message 成功提示
   * @returns {Object} 标准响应对象
   */
  static success(data, message = 'success') {
    return {
      code: 200,
      message,
      data,
      timestamp: Date.now()
    };
  }

  /**
   * 操作失败响应
   * @param {string} message 失败提示
   * @param {number} code 错误码，默认400
   * @returns {Object} 标准响应对象
   */
  static fail(message, code = 400) {
    return {
      code,
      message,
      data: null,
      timestamp: Date.now()
    };
  }

  /**
   * 错误响应
   * @param {string} message 错误提示
   * @param {number} code 错误码，默认500
   * @returns {Object} 标准响应对象
   */
  static error(message, code = 500) {
    return {
      code,
      message,
      data: null,
      timestamp: Date.now()
    };
  }

  /**
   * 资源不存在响应
   * @param {string} message 提示信息
   * @returns {Object} 标准响应对象
   */
  static notFound(message = '资源不存在') {
    return this.fail(message, 404);
  }

  static forbidden(message = 'Forbidden') {
    return {
      code: 403,
      message,
      data: null,
      timestamp: Date.now()
    };
  }

  static unauthorized(message = 'Unauthorized') {
    return {
      code: 401,
      message,
      data: null,
      timestamp: Date.now()
    };
  }

  static badRequest(message = 'Bad Request') {
    return {
      code: 400,
      message,
      data: null,
      timestamp: Date.now()
    };
  }

  static custom(code, message, data = null) {
    return {
      code,
      message,
      data,
      timestamp: Date.now()
    };
  }
}

/**
 * 将驼峰命名转换为下划线命名
 * @param {Object} data - 需要转换的对象
 * @param {Object} fieldMap - 字段映射，格式为 { 驼峰字段: 下划线字段 }
 * @returns {Object} - 转换后的对象
 */
function formatFieldNames(data, fieldMap) {
  if (!data || typeof data !== 'object') {
    return data;
  }
  
  const result = { ...data };
  
  Object.entries(fieldMap).forEach(([camelKey, snakeKey]) => {
    // 只有当驼峰命名的字段存在时才进行转换
    if (data[camelKey] !== undefined) {
      result[snakeKey] = data[camelKey];
      
      // 可以选择是否删除原有的驼峰命名字段
      // delete result[camelKey];
    }
  });
  
  return result;
}

module.exports = {
  ResultCode,
  ApiResponse,
  formatFieldNames
}; 